﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;

namespace WorkBasket.Controllers.Api
{
    public class UnitController : ApiController
    {
        private SOC soc = new SOC(new MyContext());
 



        [Route("api/unit/save")]
        public IHttpActionResult Post([FromBody]  Unit value)
        {
             try{
                bool IsNew=false;


                if(value.UnitID==0){

                    IsNew = true;
                     soc.Units.Add(value);
                }  else
                {
                    soc.Units.Update(value);
                }
 
                soc.CommitChanges();

                 


                if(IsNew){
                    Group grp = new Group();
                    grp.GroupName = "Administrators";
                    grp.UnitID = value.UnitID;
                    soc.Groups.Add(grp);
                    soc.CommitChanges();
                    GroupMember grpMem = new GroupMember();
                    grpMem.UserID = "0";
                    grpMem.GroupID = grp.GroupID;
                    soc.GroupMembers.Add(grpMem);
                    soc.CommitChanges();

                }


            
                return Json(new DataReturn(string.Empty, value));
            }
            catch (Exception e)
            {
                return new System.Web.Http.Results.ExceptionResult(e, this);
            }
        }
    }
}
